package menu

import (
	"context"
	// "fmt"

	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenuListByRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetMenuListByRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuListByRoleLogic {
	return &GetMenuListByRoleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: menu
func (l *GetMenuListByRoleLogic) GetMenuListByRole(in *backend.BaseMsg) (*backend.MenuListResp, error) {
	// logrus.Info(fmt.Sprintf("PageInfoReq: %+v", in))

	if in.Msg == "" {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	preFilterMap := make(map[string]map[string][]any)
	if codes := modelx.UniqueInterfaces(in.Msg, 0); len(codes) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	} else {
		preFilterMap[model.SysRoleColumns.Code] = map[string][]any{
			"in": codes,
		}
	}

	roles, _, err := l.svcCtx.SysRole.GetList(l.ctx, model.M{
		"orderBy": model.SysRoleColumns.Sort,
		"select":  ",",
	}, -1, preFilterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	resp := &backend.MenuListResp{}
	if len(roles) == 0 {
		return resp, nil
	}

	var roleIds []any
	for _, role := range roles {
		roleIds = append(roleIds, role.ID)
	}

	relFilterMap := make(map[string]map[string][]any)
	relFilterMap[model.SysRoleMenuRelationshipColumns.RoleID] = map[string][]any{
		"in": roleIds,
	}
	rels, _, err := l.svcCtx.SysRole.GetRelMenuList(l.ctx, model.M{
		"select": model.SysRoleMenuRelationshipColumns.MenuID,
	}, -1, relFilterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(rels) == 0 {
		return resp, nil
	}

	var menuIds []any
	for _, rel := range rels {
		menuIds = append(menuIds, rel.MenuID)
	}

	filterMap := make(map[string]map[string][]any)
	filterMap[model.SysMenuColumns.ID] = map[string][]any{
		"in": menuIds,
	}
	menus, _, err := l.svcCtx.SysMenu.GetList(l.ctx, model.M{
		"orderBy": model.SysMenuColumns.Sort,
	}, -1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	resp.Total = uint64(len(menus))

	for _, v := range menus {
		resp.List = append(resp.List, &backend.MenuInfo{
			Id:        &v.ID,
			ParentId:  &v.ParentID,
			Type:      pointy.GetPointer(uint32(v.MenuType)),
			Level:     pointy.GetPointer(uint32(v.MenuLevel)),
			Path:      &v.Path,
			Name:      &v.Name,
			Redirect:  &v.Redirect,
			Component: &v.Component,
			Sort:      pointy.GetPointer(uint32(v.Sort)),
			Status:    pointy.GetPointer(uint32(v.Status)),
			CreatedAt:   pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
			UpdatedAt:   pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
			DeletedAt:   pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
			Meta: &backend.MenuMeta{
				Title:              &v.Title,
				Icon:               &v.Icon,
				HideMenu:           pointy.GetPointer(uint32(v.HideMenu)),
				HideBreadcrumb:     pointy.GetPointer(uint32(v.HideBreadcrumb)),
				IgnoreKeepAlive:    pointy.GetPointer(uint32(v.IgnoreKeepAlive)),
				HideTab:            pointy.GetPointer(uint32(v.HideTab)),
				FrameSrc:           &v.FrameSRC,
				CarryParam:         pointy.GetPointer(uint32(v.CarryParam)),
				HideChildrenInMenu: pointy.GetPointer(uint32(v.HideChildrenInMenu)),
				Affix:              pointy.GetPointer(uint32(v.Affix)),
				DynamicLevel:       pointy.GetPointer(uint32(v.DynamicLevel)),
				RealPath:           &v.RealPath,
			},
		})
	}

	return resp, nil
}
